/**
 * Created by Administrator on 2017/1/12.
 */
$(function () {
    typhoonMap.init("map");

    $(".tool_zoom_in").click(function(){typhoonMap.zoomIn();});
    $(".tool_zoom_out").click(function(){typhoonMap.zoomOut();});
    $(".tool_zoom_center").click(function(){typhoonMap.map.setView(typhoonMap.defCenter, typhoonMap.defZoom);});
    $(".tool_measure").click(function(){
        typhoonMap.measure();
        $(this).attr("id","mselected");
    });

    $(".tool_change_map").click(function () {
        var layerName = $(this).attr('layer-name');
        typhoonMap.changeTilelayer(layerName);
    });

    $('#query_btn').click(function () {
        if($(".query_windfarm p").hasClass("selected")){ //风电场查询
            $(".statistical_result").show();
            //处理每个台风的最大风速问题
        }
        $(".query_result").show();
        $("#simple_detail").empty();
        $("#simple_label").empty();
        $("#date_zhcx").empty();//先清空数据
        $("#date_zhcx").prev(".show_result").html("");
        query_tf_data();
    });

    //台风登陆强度选择
    $('li.typhoon_type>input:checkbox').click(function () {
        var strengthInput = $('#queryForm').find('input[name="strength"]');
        if ($(this).is(':checked')) {
            $(strengthInput).val($(strengthInput).val() + "," + $(this).val());
        } else {
            $(strengthInput).val($(strengthInput).val().replace("," + $(this).val(), ""));
        }
    });
    $('#list_ic_title').on("change","#query_ic_small",function(){
        var year = $(this).val();
        queryYear(year);
    });
    // TODO 实时台风相似台风路径 列表点击事件
    $("#data_list_ic_real").on("click", 'li', function () {
        var ty = $(this).find(".typhoon_no").attr("ty");
        var tfbh = $(this).find(".typhoon_no").attr("bh");
        $("#simple_detail").empty();
        $("#simple_label").empty();
        var typhoonDetail = $(".typhoon_detail");
        if (!$(this).find(".typhoon_no").hasClass("typhoon_no_color")) {
            typhoonDetail.show();
            $(this).find(".typhoon_no").addClass("typhoon_no_color").siblings().addClass("typhoon_name_color");
            queryTfDitails(ty, tfbh);
        } else {
            typhoonMap.resetTyphoonLayers(tfbh);
            typhoonDetail.hide();
            $(this).find(".typhoon_no").removeClass("typhoon_no_color").siblings().removeClass("typhoon_name_color");
        }
    });
    // TODO 一般查询列表中 点击台风绑定事件
    $("#data_list_ic").on("click", 'li', function () {
        $("#query_ic_detail").empty();//先清空原有数据
        $("#query_ic_label").html('');//先清空原有数据
        var ty = $(this).find(".typhoon_no").attr("ty");
        var tfbh = $(this).find(".typhoon_no").attr("bh");
        if (!$(this).find(".typhoon_no").hasClass("typhoon_no_color")) {
            $(this).find(".typhoon_no").addClass("typhoon_no_color").siblings().addClass("typhoon_name_color");
            queryLsDetails(ty, tfbh);
        } else {
            typhoonMap.resetTyphoonLayers(tfbh);
            $(this).find(".typhoon_no").removeClass("typhoon_no_color").siblings().removeClass("typhoon_name_color");
        }
    });
    $('select.time_select').change(function () {
        var beginTime = $('#queryForm').find('input[name="beginTime"]');
        var endTime = $('#queryForm').find('input[name="endTime"]');
        if ($(this).hasClass('start')) {
            var byear = $('#byear').val();
            var bmonth = $('#bmonth').val();
            if (bmonth < 10) {
                bmonth = "0" + bmonth;
            }
            var bday = $('#bday').val();
            if (bday < 10) {
                bday = "0" + bday;
            }
            $(beginTime).val(byear + "-" + bmonth + "-" + bday + " 00:00:00");
        } else {
            var eyear = $('#eyear').val();
            var emonth = $('#emonth').val();
            if (emonth < 10) {
                emonth = "0" + emonth;
            }
            var eday = $('#eday').val();
            if (eday < 10) {
                eday = "0" + eday;
            }
            $(endTime).val(eyear + "-" + emonth + "-" + eday + " 23:59:59");
        }

    });

    $('#simple_detail').delegate('tr','click',function () {
        var tfbh = $(this).parent().attr('tfbh');
        var idx = $(this).attr('idx');
        //console.info(tfbh+':'+idx);
        var j=0;
        $.each(typhoonMap.t_layers[tfbh].t_path_point_layers._layers,function (i, obj) {
            if(idx==j){
                var layerid = obj._leaflet_id;
                //typhoonMap.map.setView(obj._latlng, typhoonMap.defZoom);
                typhoonMap.map.panTo(obj._latlng);
                typhoonMap.t_layers[tfbh].t_path_point_layers.getLayer(layerid).fire('click');
            }
            j++;
        });
    });
    $('#simple_detail').delegate('tr','mouseover',function () {
        var tfbh = $(this).parent().attr('tfbh');
        var idx = $(this).attr('idx');
        var j=0;
        $.each(typhoonMap.t_layers[tfbh].t_path_point_layers._layers,function (i, obj) {
            if(idx==j){
                var layerid = obj._leaflet_id;
                typhoonMap.t_layers[tfbh].t_path_point_layers.getLayer(layerid).fire('mouseover');
            }
            j++;
        });
    });
    $('#simple_detail').delegate('tr','mouseout',function () {
        var tfbh = $(this).parent().attr('tfbh');
        var idx = $(this).attr('idx');
        var j=0;
        $.each(typhoonMap.t_layers[tfbh].t_path_point_layers._layers,function (i, obj) {
            if(idx==j){
                var layerid = obj._leaflet_id;
                typhoonMap.t_layers[tfbh].t_path_point_layers.getLayer(layerid).fire('mouseout');
            }
            j++;
        });
    })
});
function queryYear(year) {
    $.ajax({
        url: '/tf/main.json',
        data: {year:year},
        type: 'post',
        dataType: 'json',
        success: function (data) {
            var datas=data.data;
            $("#query_ic_label").empty();
            $("#query_ic_detail").empty();
            $("#data_list_ic").empty();//先清空数据
            if(datas.length>0){
                $.each(datas, function (key, value) {
                    if (value.chnname == '' || value.chnname == 'null' || value.chnname == null) {
                        value.chnname = '';
                    }
                    var html = '<li>' +
                        '<div class="typhoon_no" bh="' + value.tfbh + '" ty="' + value.ty + '">' + value.tfbh + '</div>' +
                        '<div class="typhoon_name">' + value.chnname + '&nbsp' + value.name + '</div>' +
                        '</li>';
                    $("#data_list_ic").append(html);
                });
            }
        }
    });
}
function strToObj(str) {
    str = str.replace(/&/g, "','");
    str = str.replace(/=/g, "':'");
    str = "({'" + str + "'})";
    obj = eval(str);
    return obj;
}
function query_tf_data() {
    //清空地图
    typhoonMap.resetTyphoonLayers();

    var paramsObjStr = $("#queryForm").serialize();
    paramsObjStr = decodeURIComponent(paramsObjStr, true);
    // paramsObjStr = encodeURI(encodeURI(paramsObjStr));
    var paramsObj = strToObj(paramsObjStr);
    if($(".query_item.query_normal").find('.selected').length==1){
        removeUnusedParam(paramsObj);
    }
// 根据编号查询台风
    // TODO 其他方式查询后需添加并处理多个条件之间的关系
    var tfbh = paramsObj.tfbhs;
    if (tfbh!=null && tfbh != '') {
        var params = {tfbhs: tfbh};
        queryTfbhs(params);
    } else {//如果不用编号查询的话就进行其他方面的查询
        queryTfbhs(paramsObj);
    }
}

function removeUnusedParam(paramsObj) {
    $(".query1ist_2 .query_type p").each(function (index, item) {
        // console.info(index+item);
        var query_type = $(item).attr('query-type');
        var isActive = $(item).hasClass('active');
        if(!isActive){
            if(query_type=="tfbh"){
                paramsObj.tfbhs = null;
            }else if(query_type=="latlng"){
                paramsObj.latlngType = null;
            }else if(query_type=="time"){
                paramsObj.beginTime = null;
                paramsObj.endTime = null;
            }else if(query_type=="landcity"){
                paramsObj.landCity = null;
                paramsObj.dlprovince1 = null;
                paramsObj.dlcity1 = null;
                paramsObj.dlprovince2 = null;
                paramsObj.dlcity2 = null;
            }else  if(query_type=="landinfo"){
                paramsObj.dlbefore = null;
            }
        }
    })
}
// TODO 实时台风路径
function realTimeTf(){
    var tfbh=$('.query_realtime p').attr("tfbh");
    var obl=$('.query_realtime p');
    if(tfbh!=''){
        typhoonMap.resetTyphoonLayers(tfbh);
        $(obl).attr("tfbh","");
    }else{
        $.ajax({
            url: '/tfData/tf_path_data/realtime.ajax',
            type: 'get',
            dataType: 'json',
            success: function (data) {
                $(obl).attr("tfbh",data.tfbh);
                typhoonMap.drawTyphoon_(data);
            }
        });
    }
}
//查询相对应的台风
function queryTfbhs(params) {
    $.ajax({
        url: '/tf/main.json',
        data: params,
        type: 'post',
        dataType: 'json',
        success: function (data) {
            var datas=data.data;
            // TODO 台风数据
            $("#date_zhcx").empty();//先清空数据
            $("#max_tffs").empty();//最大风速
            $("#date_zhcx").prev(".show_result").html("搜索到" + datas.length + "条结果");
            $.each(datas, function (key, value) {
                if (value.chnname == '' || value.chnname == 'null' || value.chnname == null) {
                    value.chnname = '';
                }
                var html = '<li>' +
                    '<div class="typhoon_no" bh="' + value.tfbh + '" ty="' + value.ty + '">' + value.tfbh + '</div>' +
                    '<div class="typhoon_name">' + value.chnname + '&nbsp' + value.name + '</div>' +
                    '</li>';
                var hs="<tr>" +
                    "<td>" + value.tfbh + "-" + value.chnname + value.name + "</td>"+
                    "<td>"+ value.maxWind +"m/s</td>"+
                    "</tr>";

                $("#date_zhcx").append(html);
                $("#max_tffs").append(hs);
            });

            // TODO 台风频次
            var strength=data.strength;
            $("#count_tfpc").empty();//台风频次
            for(var k in strength){
                var hs="<tr>" +
                    "<td>"+typhoonConstants.typhoon_strengthDesc[k]+"</td>"+
                    "<td>"+strength[k]+"</td>"+
                    "</tr>";
                $("#count_tfpc").append(hs);
            }

        },
        error: function(){
            $("#date_zhcx").prev(".show_result").html("搜索到0条结果");
        }
    });
}
$("#date_zhcx").on("click", 'li', function () {
    var ty = $(this).find(".typhoon_no").attr("ty");
    var tfbh = $(this).find(".typhoon_no").attr("bh");
    $("#simple_detail").empty();
    $("#simple_label").empty();
    var typhoonDetail = $(".typhoon_detail");
    if (!$(this).find(".typhoon_no").hasClass("typhoon_no_color")) {
        typhoonDetail.show();
        $(this).find(".typhoon_no").addClass("typhoon_no_color").siblings().addClass("typhoon_name_color");
        queryTfDitails(ty, tfbh);
    } else {
        typhoonMap.resetTyphoonLayers(tfbh);
        typhoonDetail.hide();
        $(this).find(".typhoon_no").removeClass("typhoon_no_color").siblings().removeClass("typhoon_name_color");
    }

});

function queryLsDetails(ty,tfbh){ //历史台风
    $.ajax({
        url: '/tfData/tf_path_data/' + ty + '/' + tfbh + '.ajax',
        type: 'get',
        dataType: 'json',
        success: function (data) {
            typhoonMap.drawTyphoon_(data);
            $("#query_ic_detail").empty();//先清空数据
            if (data.name == '' || data.name == 'null' || data.name == null) {
                data.name = '';
            }
            $("#query_ic_label").html(data.name + '-' + tfbh + '-路径简报');
            $.each(data.pathData, function (key, value) {
                var html = '<tr>' +
                    '<td>' + timeFn(value.datetime) + '</td>' +
                    '<td>' + value.windv + 'm/s</td>' +
                    '<td>' + changeTfDitails(value.movedir) + '</td>' +
                    '<td>' + getStrength(value.strength) + '</td>' +
                    '</tr>';
                $("#query_ic_detail").append(html);
            });
        }
    });
}

function getStrength(strength){
    var temp = "";
    if($.trim(strength)!=""&&$.trim(strength)!=null&&$.trim(strength)!="null"){
        temp = typhoonConstants.typhoon_strengthDesc[strength];
    }
    return temp;
}

function changeTfDitails(movedir){
    var rs="";
    if(movedir!=null&&movedir!="ALMOST"&&movedir.length>0 ){
        var sp=new Array();
            sp=movedir.split("");
        for(var i=0;i<sp.length;i++){
            rs=rs+typhoonConstants.typhoon_direction[sp[i]];
        }
    }
    return rs;
}
function queryTfDitails(ty, tfbh) { //一般，风电场查询
    $.ajax({
        url: '/tfData/tf_path_data/' + ty + '/' + tfbh + '.ajax',
        type: 'get',
        dataType: 'json',
        success: function (data) {
            typhoonMap.drawTyphoon_(data);
            $("#simple_detail").empty();//先清空数据
            if (data.name == '' || data.name == 'null' || data.name == null) {
                data.name = '';
            }
            $("#simple_label").html(data.name + '-' + tfbh + '-路径简报');
            $("#simple_detail").attr('tfbh',tfbh);
            $.each(data.pathData, function (key, value) {
                var html = '<tr idx='+key+'>' +
                    '<td>' + timeFn(value.datetime) + '</td>' +
                    '<td>' + value.lon + '</td>' +
                    '<td>' + value.lat + '</td>' +
                    '<td>' + value.windv + '</td>' +
                    '<td>' + value.pressure + '</td>' +
                    '</tr>';

                //时间(时),经度(E),纬度(N),最大风速(m/s),最低气压(HPA)
                $("#simple_detail").append(html);
            });
        }
    });
}
function timeFn(time){
    var newTime=time.split(":")[0];
    return newTime+"时";
}
/**
 * 导出数据
 * @param type 数据类型
 */
function exportDate(type){
    var datelist=$("#date_zhcx").find(".typhoon_no.typhoon_no_color");
    var tys="";var bhs="";
    if(datelist.length>0){
        for(var i=0;i<datelist.length;i++){
            if(tys.length>0){
                tys=tys+","+$(datelist[i]).attr("ty");
                bhs=bhs+","+$(datelist[i]).attr("bh");
            }else{
                tys=$(datelist[i]).attr("ty");
                bhs=$(datelist[i]).attr("bh");
            }
        }
    }
    if(tys.length>0){
        window.location.href="/tfData/exportDatasToExcel?tys="+tys+"&bhs="+bhs+"&exceltype="+type;
    }
}
function exportDate1(type){
    var datelist=$("#data_list_ic_real").find(".typhoon_no.typhoon_no_color");
    var tys="";var bhs="";
    if(datelist.length>0){
        for(var i=0;i<datelist.length;i++){
            if(tys.length>0){
                tys=tys+","+$(datelist[i]).attr("ty");
                bhs=bhs+","+$(datelist[i]).attr("bh");
            }else{
                tys=$(datelist[i]).attr("ty");
                bhs=$(datelist[i]).attr("bh");
            }
        }
    }
    if(tys.length>0){
        window.location.href="/tfData/exportDatasToExcel?tys="+tys+"&bhs="+bhs+"&exceltype="+type;
    }
}

L.drawLocal = {  //绘图提示文字
    draw: {
        handlers: {
            circle: {
                tooltip: {
                    start: '单击并拖动绘制圆'
                },
                radius: '半径(1ft=0.3048m)'
            },
            polygon: {
                tooltip: {
                    start: '单击开始绘制形状',
                    cont: '点击继续绘制形状',
                    end: '单击第一个点或双击最后点完成绘制'
                }
            },
            polyline: {
                error: '<strong>错误:</strong> 无效的图形!',
                tooltip: {
                    start: '单击开始绘制线',
                    cont: '点击继续绘制线',
                    end: '点击最后一个点完成绘制'
                }
            },
            rectangle: {
                tooltip: {
                    start: '单击并拖动绘制矩形'
                }
            },
            simpleshape: {
                tooltip: {
                    end: '释放鼠标完成绘图'
                }
            }
        }
    }
};

function drawRectangle() {
    typhoonMap.drawn.drawRectangle(typhoonMap.map,null,function (e) {
        var lefttop = e.layer._latlngs[1];
        var rightbottom = e.layer._latlngs[3];
        $('#rect_maxlat').val(lefttop.lat.toFixed(3));
        $('#rect_minlon').val(lefttop.lng.toFixed(3));
        $('#rect_minlat').val(rightbottom.lat.toFixed(3));
        $('#rect_maxlon').val(rightbottom.lng.toFixed(3));
    });
}

function drawCircle() {
    typhoonMap.drawn.drawCircle(typhoonMap.map,null,function (e) {
        var r = e.layer._mRadius /1000.00;
        var latlng = e.layer._latlng;
        $('#circle_r').val(r.toFixed(3));
        $('#circle_lat').val(latlng.lat.toFixed(3));
        $('#circle_lng').val(latlng.lng.toFixed(3));
    });
}

function drawPolygon() {
    typhoonMap.drawn.drawPolygon(typhoonMap.map,null,function (e) {
        var latlngs = e.layer._latlngs.toString().replace(new RegExp('LatLng','g'),"");
        $('#area_polygon').text(latlngs);
        $('#area_polygon_val').val(latlngs);
    });
}